package com.wxd.modules.sys.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wxd.annotation.DataFilter;
import com.wxd.modules.common.redis.SysDeptRedis;
import com.wxd.modules.sys.dao.SysDeptDao;
import com.wxd.modules.sys.dao.SysRoleDao;
import com.wxd.modules.sys.entity.SysDeptEntity;
import com.wxd.modules.sys.entity.SysRoleEntity;
import com.wxd.modules.sys.service.SysDeptService;
import com.wxd.modules.sys.service.SysRoleDeptService;
import com.wxd.modules.sys.service.SysRoleService;
import com.wxd.modules.sys.shiro.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 部门
 */
@Service("sysDeptService")
public class SysDeptServiceImpl extends ServiceImpl<SysDeptDao, SysDeptEntity> implements SysDeptService {
    @Autowired
    private SysDeptRedis sysDeptRedis;
    @Autowired
    private SysRoleDeptService sysRoleDeptService;
    @Override
    @DataFilter(subDept = true,user = false,tableAlias = "t1")
    public List<SysDeptEntity> queryList(Map<String, Object> map) {
        List<SysDeptEntity> sysDeptEntities;
        //得到登录角色的Id，登录角色对应着数据权限
        Long roleId = (Long) ShiroUtils.getSession().getAttribute("roleId");
        if(sysDeptRedis.get(roleId+"")==null)
        {
            sysDeptEntities= baseMapper.queryList(map);
            sysDeptRedis.saveOrUpdate(roleId+"",sysDeptEntities);
            System.out.println("缓存中不存在"+sysDeptRedis.get(roleId+""));
        }
        else
        {
            System.out.println("缓存中存在"+sysDeptRedis.get(roleId+""));
            sysDeptEntities=sysDeptRedis.get(roleId+"");
        }
        return sysDeptEntities;
    }

    @Override
    public List<Long> queryDeptIdList(Long parentId) {
        return baseMapper.queryDeptIdList(parentId);
    }

    @Override
    public List<Long> getSubDeptIdList(Long deptId) {
        //部门及子部门Id列表
        List<Long> deptIdList=new ArrayList<>();
        //获取子部门Id
        List<Long> subIdList = queryDeptIdList(deptId);
        getDeptTreeList(subIdList,deptIdList);
        return deptIdList;
    }
    /*查询父部门ID*/
    @Override
    public List<Long> queryParentIdList(Long deptId) {
        return baseMapper.queryParentIdList(deptId);
    }

    /**
     * 递归
     */
    private void getDeptTreeList(List<Long> subIdList,List<Long> deptIdList)
    {
       for(Long deptId:subIdList)
       {
           List<Long>  list= queryDeptIdList(deptId);
           if(list.size()>0)
           {
                 getDeptTreeList(list,deptIdList);
           }
           deptIdList.add(deptId);
       }
    }
}
